<template>
	<div class="container-fluid" :id="isFullScreen?'fullScreen':''">
    <div class="row">
        <b-alert class="topCenter" :variant="variant"
                 dismissible
                 fade
                 :show="showMsg">
          {{ msg }}
        </b-alert>
        <BlogCat :categories="categories" :curCat="category"></BlogCat>

        <div class="col col-lg-3 articles" >
          <p class="add_article" v-if="currentCatName!='回收站'">
            <button class="btn btn-primary" @click="addArticle"><i class="fa fa-plus"></i> {{ currentCatName }} {{ currentId }}</button>            
          </p>
          

            
          <ul class="list-group list-group-flush" v-if="articlesList">
            <li class="list-group-item" v-for="(article,index) in articlesList.data" :key="article.id" @click="editArticle(index)"><router-link :to="{ name: 'article', params: { id: article.id }}" :class="article.status+(selectIndex==index?' hover':'')"><i class="c"></i> {{ article.title }}
                        <div>
                          <i class="fa fa-cog" aria-hidden="true"></i>
                          <span>
                            <ul class="_3FcHm">
                                <li class="_2po2r cRfUr" title="" v-if="article.status==='published'" @click="preview"><i class="fa fa-external-link _22XWG"></i>预览文章</li>
                              <template v-if="article.status!=='trashed'">
                                <li class="_2po2r cRfUr" title="" @click="published"><i class="fa fa-share _22XWG"></i>直接发布</li>                      
                                <li class="_2po2r cRfUr" title="" v-b-modal.mov-article><i class="fa fa-folder-open _22XWG"></i>移动文章</li>
                                <li class="_2po2r cRfUr" title="" v-b-modal.del-article><i class="fa fa-trash-o _22XWG"></i>删除文集</li>
                              </template>
                              <template v-if="article.status==='trashed'">
                                <li class="_2po2r cRfUr" title="" @click="restore"><i class="fa fa-share _22XWG"></i>恢复文章</li>
                              </template>
                            </ul>
                          </span>
                        </div>
            </router-link></li>
          </ul>

          <b-pagination v-if="showPagination" size="md" @change="goPage" :total-rows="articlesList.total" v-model="current_page" :per-page="parseInt(articlesList.per_page)"></b-pagination>


          <b-modal id="mov-article" centered title="移动文章"  @ok="moveArticle" cancel-title="取消" ok-title="确定">
            <b-form-select class="mb-3" v-model="movCategory">
              <option v-for="cat in categories" :disabled="cat.id==category.id" :value="cat.id">{{ cat.name }}</option>
            </b-form-select>
          </b-modal>
          <b-modal id="del-article" centered title="删除文章"  @ok="delArticle" cancel-title="取消" ok-title="确定">
              确定要移动文章`<code>{{ title }}</code>`到回收站吗?
          </b-modal>
        </div>
        <div class="col col-lg-7">

            <b-form-input placeholder="请输入标题" v-model.trim="title" v-if="currentCatName!='回收站'"></b-form-input>
         

        		<div id="editor" @paste="paste" v-if="currentCatName!='回收站'">
        			<ul class="_3LYoB clearfix">		
        				<li class="_2zLpt" data-index="0"><a @click="getPos" v-b-modal.modal-center  title="上传图片"><i class="fa fa-picture-o"></i></a></li>
        				<li class="tGbI7 cztJE" data-index="2"><a @click="published"><i class="fa fa-mail-forward"></i> 发布文章</a></li>
        				<li class="_2zLpt tGbI7" data-index="1"><a @click="fullScreen"  :title="isFullScreen?'退出全屏':'全屏'"><i class="fa fa-expand"></i></a></li>
        				<li class="_2zLpt tGbI7" data-index="1"><a title="保存" @click="save"><i class="fa fa-floppy-o"></i></a></li>
        			</ul> 
        			<textarea id="textMarkdown" :value="input" @input="update" :style="autoheight"></textarea> 
        			<div id="htmlMarkdown" v-html="compiledMarkdown" :style="autoheight"></div> 
        		</div>
        		<b-modal id="modal-center" @cancel="cancelUpload" @ok="confirmUpload" cancel-title="取消" ok-title="确定" centered title="上传图片">
        		    <p class="my-4">
        		    	<b-form-file capture multiple ref="fileinput" v-model="files" :state="Boolean(files)" placeholder="Choose a file..."></b-form-file>
                  <div ref="select_frame" class="drop_box">
                      将文件拖拽到这里
                  </div>
        		    	<span v-if="selectFile">
        		    		<img style="width:100px" v-for="img in imgs" :src="img.src" :title="img.name"/>
        		    	</span>
        		    </p>
        		</b-modal>
          </div>
      </div>
	</div>
</template>

<style type="text/css">
.topCenter{position:fixed;width:320px;top:90px;z-index:1000;left:50%;margin-left:-160px;}
.container-fluid{background-color:#FFF;position:fixed;left:0;top:0;z-index:1000;}
.categories,.articles{padding-left:0;padding-right:0;}
.articles{position:relative;}
.articles ul.list-group{height:80%;}
.articles ul.pagination{position:absolute;bottom:0px;left:10px;}
.articles .list-group-item{padding:0;height:10%;max-height: 70px;}
.articles .list-group-item a{display:block;height:97%;width:100%;padding:10px;line-height: 40px;color:#333;border-left:3px solid #e6e6e6;background-color:#e6e6e6;position:relative;}
.articles .list-group-item a.hover{ border-left-color: #ec7259;}
.articles .list-group-item a.published i.c{
    background: url(/img/sprite.9d24217.png) no-repeat -50px -25px;
        background-size: auto auto;
    background-size: 250px;float:left;margin:5px;height:30px;width:23px;
}

.list-group-item i{margin-right:4px;}
.articles .list-group-item a i.c{
    background: url(/img/sprite.9d24217.png) no-repeat -0px -25px;
        background-size: auto auto;
    background-size: 250px;float:left;margin:5px;height:30px;width:23px;
}

.articles  .list-group-item div{position:absolute;width:30px;height:30px;line-height:30px;text-align:center;display:none;right: 20px;
top: 15px;z-index:888;}
.articles  .list-group-item div span {
    display: block;
    margin-right: 20px;
    -o-text-overflow: ellipsis;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.articles .list-group-item a.hover div{
  display:block;
}
.articles  .list-group-item div:hover span ul{
  display:block;
}
.articles  .list-group-item div span ul{
  position:absolute;
  display:none;
  left: -60px;
  box-shadow: 0 5px 10px rgba(0,0,0,.2);
  top: 30px;
  z-index:1000;
  background-color:#FFF;
  border-radius:5px;
  color:#333;
  list-style:none;
  padding-left: 0px;
  padding-right:0px;
  padding-top: 3px;
  padding-bottom: 3px;
}
.articles  .list-group-item div span ul._3FcHm::before {
    border-left: 9px solid transparent;
    border-right: 9px solid transparent;
    border-bottom: 9px solid #fff;
    top: -9px;
    position: absolute;
    right: 12px;
    content: "";
    display: inline-block;
}
.articles  .list-group-item div span ul._3FcHm li{line-height:40px;height:40px;border-bottom:1px solid silver;padding:0 10px;cursor:pointer;}
.articles  .list-group-item div span ul._3FcHm li:last-child{border-bottom:none;}
.articles  .list-group-item div span ul._3FcHm li:hover{background-color:#333;color:#FFF;}

#fullScreen{width:100%;}
#fullScreen #editor {
    position: fixed;
    z-index: 1000;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}
#fullScreen #editor textarea,#fullScreen #editor div{height:100%;}
#editor {
  margin: 0;
  height: 100%;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #333;
  background-color:#fcfaf2;
}
#editor #htmlMarkdown{overflow:scroll;max-height:100%;overflow-x: hidden;background-color:#fcfaf2;}
#editor #htmlMarkdown img{max-width:100%;}
.drop_box{border:1px dashed silver;height:45px;line-height:45px;text-align:center;}
#editor ul{height:45px;background-color:#EEE;margin-bottom:0;padding-left:15px;}
#editor ul li{list-style:none;float:left;line-height: 45px;font-size: 16px;margin-right:15px;}
#editor ul li:hover{background-color:#333;color:#FFF;}
#editor ul li.tGbI7{float:right;}
#editor ul li.cztJE{padding:0 10px;}
#editor ul li a {
    height: 45px;
    line-height: 45px;
    display: block;
    min-width: 45px;
    text-align: center;
}
#editor textarea, #editor div {
  display: inline-block;
  width: 49.7%;
  height: 100%;
  vertical-align: top;
  box-sizing: border-box;
  padding: 0 2px;
  height:90%;
}
#editor textarea {
  border: none;
  border-right: 1px solid #ccc;
  resize: none;
  outline: none;
  background-color: #f6f6f6;
  font-size: 14px;
  font-family: 'Monaco', courier, monospace;
  padding: 20px;
}
#editor code {
  color: #f66;
}
.add_article{font-size:18px;text-indent:10px;padding-top:20px;padding-bottom:10px;}
.add_article a{color:#333;} 
</style>
<script>	
var tmpheight=document.documentElement.clientHeight;
var newheight='height:'+(tmpheight-83)+'px';
var fullheight='height:'+(tmpheight-45)+'px';

import BlogCat from './blog-cat'
import VueRouter from 'vue-router'
Vue.use(VueRouter);

const routes = [
  { path: '/article/:id',name:'article',component:resolve => require(['./WriterComponent.vue'], resolve)},
]

var myMarked = require('marked');
import 'highlight.js/styles/github.css';
// Set options
// `highlight` example uses `highlight.js`
myMarked.setOptions({
  renderer: new myMarked.Renderer(),
  highlight: function(code) {
    return require('highlight.js').highlightAuto(code).value;
  },
  pedantic: false,
  gfm: true,
  tables: true,
  breaks: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  xhtml: false
});
(function ($, undefined) {
    $.fn.getCursorPosition = function () {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);





var markdown='';
if(localStorage.getItem('markdown')){
	markdown=localStorage.getItem('markdown');
}

const router = new VueRouter({
  routes // short for `routes: routes`
})

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

export default {
   router,
   data(){
		return {
      autoheight:newheight,
      loading:false,
      show:true,
      showMsg:false,
      showPagination:false,
      variant:'success',
      msg:'alert some message',
      article_id:null,
      current_page:1,
			input:markdown,
      articlesList:null,
      selectIndex:0,
      currentArticle:null,
      oldCategory_id:null,
      category:null,
      movCategory:null,
      title:'',
      categories:[],
      isFullScreen:false,
			imgs:[],
			pos:0,
    		files:null
		}
   },
   components: {
      BlogCat
    },
   computed: {
      currentId () {
        var currentId=this.$route.params.id;
        if(currentId&&!this.loading){
            source.cancel('Operation canceled by the user.');
            var that=this;
            axios.get('/rbac/blog/apiArticle?c',{
              params:{currentId:currentId}
            })
              .then(function (response) { 
                  var res=response.data;
                  that.current_page=res['page'];
                  that.categories=res['categories'];
                  that.currentArticle=res['currentArticle'];
                  that.title=res['currentArticle'].title;
                  that.input=res['currentArticle'].markdown;
                  that.article_id=res['currentArticle'].id;
                  if(res['hasCat']){
                      that.category=res['currentArticle'].category;
                  }else{
                      if(res['categories'].length>0){
                          that.category=res['categories'][0];                  
                      }
                  }

                  that.loading=true;
                  return currentId;
              })
              .catch(function(error) {
                 return currentId;
              });                  
        }else{
          return null;
        }
        
      },
      currentCatName:function(){
        var that=this;
        if(that.category!=null){
            var params={};
            var current_page=this.$route.params.current_page||this.current_page;
            var category_id=null;
            var catName=null;
            if(that.category.trash){
              category_id='trashed';
              catName='回收站';
              params={category_id:category_id,page:current_page,per_page:10};
              console.log('get tha articles of the trash');
            }else{
              category_id=that.category.id;
              catName=that.category.name;
              params={category_id:category_id,page:current_page,per_page:10};
              console.log('get tha articles of the category ',that.category.id);
            }
            if(category_id!=that.oldCategory_id){
                that.oldCategory_id=category_id;
            }else{
                console.log('the category not change...');
                return catName;
            }
            

            axios.get('/rbac/article/apiList',{params:params})
                 .then(function (response) {
                    that.articlesList=response.data;  
                    that.current_page=response.data.current_page;
                    var artList= response.data.data;
                    console.log('change the article selected ',that.article_id)
                    for (var i = artList.length - 1; i >= 0; i--) {
                        if(artList[i].id==that.article_id){
                          console.log('equal....')
                          that.selectIndex=i;
                        }
                    }  
                    if(artList.length>0){
                      that.showPagination=true;   
                    }          
                 })
                 .catch(function (error) {
                    console.log(error);
                 });
            return catName;
        }else{
          return null;
        }     
      },
      compiledMarkdown: function () {
	      return myMarked(this.input)
	    },
	    selectFile: function(){
	      if(this.files && this.files.length>0){
	        let name='';
	        let imgs=[];
	        _.forEach(this.files,function(file){
	          var reader  = new FileReader();
	          reader.addEventListener("load", function () {
	            imgs.push({name:file.name,src:reader.result});
	            console.log('load...'+file.name+_.now());
	          }, false);
	          reader.readAsDataURL(file);
	          name=name+file.name;
	        })
	        this.imgs=imgs;
	        return true;
	      }else{
	        return false;
	      }
	    }
   },   
   methods: {
     goPage:function(){
          var that=this;
          setTimeout(function(){
            console.log('go page...',that.current_page);
            var category_id=null;
            if(that.category.trash){
              category_id='trashed';
            }else{
              category_id=that.category.id;
            }
            var params={category_id:category_id,page:that.current_page,per_page:that.articlesList.per_page};
            axios.get('/rbac/article/apiList',{params:params})
                 .then(function (response) {
                    that.articlesList=response.data;  
                    var artList= response.data.data;
                    for (var i = artList.length - 1; i >= 0; i--) {
                        if(artList[i].id==that.currentId){
                          that.selectIndex=i;
                        }
                    }  
                    if(artList.length>0){
                      that.showPagination=true;   
                    }                             
                 })
                 .catch(function (error) {
                    console.log(error);
                 });
          },200);
      },
     alertMsg:function(msg,variant){
        this.msg=msg;
        this.variant=variant;
        this.showMsg=true;
        var that=this;
        setTimeout(function(){
          that.showMsg=false;
        },2000);
     },
     fullScreen:function(e){
          if(this.isFullScreen){
            this.autoheight=newheight;
          }else{
            this.autoheight=fullheight;
          }
          this.isFullScreen=!this.isFullScreen;
     },
     changeStatus:function(status){
        var that=this;
        var info='移动文章到回收站';
        if(status=='pending'){
          info='恢复文章';
        }
        axios.post('/rbac/article/apiMovArticle',{status:status,article_id:that.article_id})
        .then(function (response) { 
          if(response.data.msg=='success'){
            that.articlesList.data.splice(that.selectIndex,1); 
            that.alertMsg(info+'成功','success');
          }else{
            that.alertMsg(info+'失败','danger');
          }
        })
        .catch(function (error) {
          console.log(error);
        });
     },
     preview:function(){
        var that=this;
        setTimeout(function(){
          window.open('/?id='+that.article_id);
        },1000);
     },
     restore:function(){
        this.changeStatus('pending');
     },
     delArticle:function(){
        this.changeStatus('trashed');
     },
     moveArticle:function(e){
        console.log(this.movCategory,this.article_id,this.title);
        var that=this;
        axios.post('/rbac/article/apiMovArticle',{category_id:that.movCategory,article_id:that.article_id})
        .then(function (response) { 
          if(response.data.msg=='success'){
            that.articlesList.data.splice(that.selectIndex,1); 
            that.alertMsg('移动文章成功','success');
          }else{
            that.alertMsg('移动文章失败','danger');
          }
        })
        .catch(function (error) {
          console.log(error);
        });
     },
     paste:function(event){
        var pos = $('#editor textarea').getCursorPosition();
        var clipboard = event.clipboardData || event.originalEvent.clipboardData;
        var type = clipboard.items[0].type;
        var blob=null;
        if (type.match(/image/)) {
            blob = clipboard.items[0].getAsFile();            
        }else{
          _.forEach(clipboard.items,function(item){
            console.log(item.type+item.kind);
            if(item.type==='image/png'){
              blob=item.getAsFile();
              return;
            }
          });
        }
        if(blob!==null){
            var formdata=new FormData();// 创建form对象
            formdata.append('img_0',blob);// 通过append向form对象添加数据,可以通过append继续添加数据
            formdata.append('filesCount',1);
            let config = {
              headers:{'Content-Type':'multipart/form-data'}
            };  //添加请求头
            var that=this;
            axios.post('/rbac/file/apiUpload',formdata,config)
              .then(function (response) { 
                var imgFiles=response.data;
                var imgFilesString='';
                _.forEach(imgFiles,function(file){
                  imgFilesString=imgFilesString+'![default]('+file+')';
                });
                var textarea_content=that.input;
                textarea_content=textarea_content.substring(0,pos)+imgFilesString+textarea_content.substring(pos);
                localStorage.setItem('markdown',textarea_content);
                that.input=textarea_content; 
                localStorage.setItem('markdown','');               
              })
              .catch(function (error) {
                console.log(error);
              });
            event.preventDefault();
        }

   },
     update: _.debounce(function (e) {
       console.log('update'+_.now());
       this.input = e.target.value
       localStorage.setItem('markdown',this.input);
     }, 300),
     addArticle:function(){
        this.selectIndex=null;
        this.article_id=null;
        this.input='';
        this.title='';
     },
     editArticle:function(index){
        this.selectIndex=index;
        var article=this.articlesList.data[index];
        this.currentArticle=article;
        this.article_id=article.id;
        this.input=article.markdown;
        this.title=article.title;
     },
     published:function(){
        this.articleStore('published');
     },
     save:function(){
        this.articleStore('pending');
     },
     articleStore:function(status){
        if(this.title==''){
          this.alertMsg('标题不能为空','danger');
          return false;
        }
        if(this.input==''){
          this.alertMsg('文章内容不能为空','danger');
          return false;
        }
        var that=this;
        axios.post('/rbac/article/apiStore',{article_id:that.article_id,category_id:that.category.id,status:status,title:that.title,markdown:that.input,html:that.compiledMarkdown})
        .then(function (response) { 
          if(that.article_id!=null){
            that.articlesList.data[that.selectIndex]=response.data;
            that.alertMsg('更新文章成功','success');
          }else{
            that.articlesList.data.push(response.data);
            that.alertMsg('添加文章成功','success');
          }
          that.isFullScreen=false;
          that.title='';
          that.input='';
          that.article_id=null;

        })
        .catch(function (error) {
          console.log(error);
        });
     },
     uploadFiles:function(files){
      var that=this;
      var formdata=new FormData();// 创建form对象
      var filesCount=files.length;
      for (var i = 0; i <= filesCount-1; i++) {
        formdata.append('img_'+i,files[i]);// 通过append向form对象添加数据,可以通过append继续添加数据
      }
      formdata.append('filesCount',filesCount);
      let config = {
          headers:{'Content-Type':'multipart/form-data'}
      };  //添加请求头
      axios.post('/rbac/file/apiUpload',formdata,config)
        .then(function (response) { 
          var imgFiles=response.data;
          var imgFilesString='';
          _.forEach(imgFiles,function(file){
            imgFilesString=imgFilesString+'![default]('+file+')';
          });
          var textarea_content=that.input.substring(0,that.pos)+imgFilesString+that.input.substring(that.pos);
          localStorage.setItem('markdown',textarea_content);
          that.input=textarea_content;
          that.$refs.fileinput.reset();
        })
        .catch(function (error) {
          console.log(error);
        });
     },
     confirmUpload:function(){
     	  this.uploadFiles(this.files);
     },
     cancelUpload:function(){
     	this.$refs.fileinput.reset();
     },
     getPos:function(){
     	var index = $('#editor textarea').getCursorPosition();
     	console.log(index);
     	this.pos=index;
     },
     initialData:function(){   
            var that=this;
            var currentId=this.$route.params.id;
            axios.get('/rbac/blog/apiArticle',{
              cancelToken: source.token,
              params:{currentId:currentId}
            })
              .then(function (response) { 
                  var res=response.data;
                  that.categories=res['categories'];
                  that.currentArticle=res['currentArticle'];
                  if(res['hasCat']){
                      that.category=res['currentArticle'].category;
                  }else{
                      if(res['categories'].length>0){
                          that.category=res['categories'][0];                  
                      }
                  }
              })
              .catch(function(thrown) {
                  if (axios.isCancel(thrown)) {
                    console.log('Request canceled', thrown.message);
                  } else {
                    // handle error
                  }
                });        
        
     },
    
     
   },

   mounted() { 
    this.initialData()   
    console.log('Component mounted.');

    this.$refs.select_frame.ondragleave = (e) => {
      e.preventDefault();  //阻止离开时的浏览器默认行为
    };
    this.$refs.select_frame.ondrop = (e) => {
      e.preventDefault();    //阻止拖放后的浏览器默认行为
      const data = e.dataTransfer.files;  // 获取文件对象
      if (data.length < 1) {
        return;  // 检测是否有文件拖拽到页面     
      }
      this.files=data;
    };
    this.$refs.select_frame.ondragenter = (e) => {
      e.preventDefault();  //阻止拖入时的浏览器默认行为
      this.$refs.select_frame.border = '2px dashed red';
    };
    this.$refs.select_frame.ondragover = (e) => {
      e.preventDefault();    //阻止拖来拖去的浏览器默认行为
    };
  },
}
</script>